﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetAncestor/*--Info--*/]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetAncestor/*--Info--*/]
GO

CREATE PROCEDURE [dbo].[GetAncestor/*--Info--*/]
	@UserRoles TNVarCharSet READONLY,
	@PathOrId nvarchar(MAX),
	@N int,
	@TypeFilter int
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @Id bigint 
	
	EXEC GetDirectoryEntryId @PathOrId, 1, @Id = @Id OUTPUT
	
	IF @Id IS NULL RETURN 1

	DECLARE @I int = @N

	DECLARE @Name nvarchar(256)
	DECLARE @ParentId bigint
	DECLARE @CreatedOn datetime
	DECLARE @UpdatedOn datetime
	DECLARE @Type int
	
	SELECT
		@ParentId = ParentId,
		@Type = [Type],
		@Name = Name,
		@CreatedOn = CreatedOn,
		@UpdatedOn = UpdatedOn
	FROM
		DirectoryEntry
	WHERE
		Id = @Id AND dbo.HasPermission(@UserRoles, @Id, 1) = 1
	
	IF @Name IS NULL RETURN 1

	WHILE 1 = 1
	BEGIN
		IF @Type & @TypeFilter <> 0
		BEGIN
			IF @I = 0
			BEGIN
/*--ResultSelect--*/

				RETURN 0
			END
			ELSE
				SET @I -= 1
		END
		
		SET @Id = @ParentId
		SET @Name = NULL

		SELECT
			@ParentId = ParentId,
			@Type = [Type],
			@Name = Name,
			@CreatedOn = CreatedOn,
			@UpdatedOn = UpdatedOn
		FROM
			DirectoryEntry
		WHERE
			Id = @Id AND dbo.HasPermission(@UserRoles, @Id, 1) = 1
			
		IF @Name IS NULL RETURN 1
	END
END
GO
